<?php
declare(strict_types=1);

namespace App\Logic\Com;

use App\Logic\BaseUserService;
use zgldh\QiniuStorage\QiniuStorage;

/**
 * @project: 兔兔考试系统
 * @author: Mandy
 * @date: 2023/7/20
 * @link: https://www.tutudati.com/
 * @site: 微信搜索-兔兔考试系统
 */
class UserFileUploadService extends BaseUserService
{
    public function imageUpload(): array
    {
        if (request()->hasFile('image')) {
            $file = request()->file('image');
            $disk = QiniuStorage::disk('qiniu');
            $fileName = md5($file->getClientOriginalName() . time() . rand()) . '.png';
            $bool = $disk->put($fileName, file_get_contents($file->getRealPath()));
            if ($bool) {
                $path = $disk->downloadUrl($fileName);
                return ["url" => $path];
            }
            return ["url" => "", "error" => "上传失败"];
        }
        return ["url" => "", "error" => "上传文件不能为空"];
    }

    public static function imageUploadByPath(string $imagePath): array
    {
        $disk = QiniuStorage::disk('qiniu');
        $basename = pathinfo($imagePath, PATHINFO_BASENAME);
        $bool = $disk->put($basename, file_get_contents($imagePath));
        if ($bool) {
            $path = $disk->downloadUrl($basename);
            return ["url" => $path];
        }
        return ["url" => "", "error" => "上传失败"];
    }
}
